<template>
  <div class="car-detail">
    <div class="header">
      <h2>车辆详情</h2>
      <div class="header-buttons">
        <el-button type="success" @click="showVRView">VR看车</el-button>
        <el-button type="primary" @click="showCarImage">查看图片</el-button>
        <el-button type="primary" @click="handleEdit" v-if="carData">编辑车辆</el-button>
      </div>
    </div>

    <el-card v-loading="loading" class="detail-card">
      <template v-if="carData">
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="车辆ID">{{ carData.carId }}</el-descriptions-item>
          <el-descriptions-item label="车牌号">{{ carData.carNum }}</el-descriptions-item>
          <el-descriptions-item label="品牌">{{ carData.brand }}</el-descriptions-item>
          <el-descriptions-item label="指导价">{{ formatPrice(carData.guidePrice) }}</el-descriptions-item>
          <el-descriptions-item label="生产时间">{{ formatDate(carData.produceTime) }}</el-descriptions-item>
          <el-descriptions-item label="车型">{{ carData.carType }}</el-descriptions-item>
        </el-descriptions>

        <el-descriptions title="车主信息" :column="2" border class="mt-4">
          <el-descriptions-item label="车主ID">{{ carData.dealerId }}</el-descriptions-item>
          <el-descriptions-item label="车主姓名">{{ carOwnerName }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ carOwnerPhone }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{ carData.status === '0' ? '正常' : '禁用' }}</el-descriptions-item>
        </el-descriptions>
        
        <!-- 车辆详细描述 -->
        <div class="description-section mt-4">
          <h3>车辆详情</h3>
          <p>{{ carData.description || '暂无详细描述' }}</p>
        </div>
        
        <!-- 车辆特性 -->
        <div class="features-section mt-4">
          <h3>车辆特性</h3>
          <div class="features-tags">
            <el-tag 
              v-for="(feature, index) in carFeatures" 
              :key="index" 
              class="feature-tag"
            >
              {{ feature }}
            </el-tag>
            <span v-if="carFeatures.length === 0">暂无特性标签</span>
          </div>
        </div>
      </template>
      <el-empty v-else description="暂无数据" />
    </el-card>

    <!-- 预约信息 -->
    <el-card class="appointment-card mt-4" v-if="carData">
      <car-appointment-list 
        :car-id="carData.carId" 
        :is-admin="isAdmin"
        :is-user="true"
        @refresh="fetchCarDetail"
      />
    </el-card>

    <!-- 评论区 -->
    <el-card class="comment-card mt-4" v-if="carData">
      <car-comment-list 
        :car-id="carData.carId" 
        :current-user-id="currentUserId" 
        :is-admin="isAdmin"
        @refresh="fetchCarDetail"
      />
    </el-card>

    <!-- 检查记录区 -->
    <el-card class="inspection-card mt-4" v-if="carData">
      <car-inspection-list 
        :car-id="carData.carId" 
        :is-admin="isAdmin"
        @refresh="fetchCarDetail"
      />
    </el-card>

    <!-- 编辑车辆对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
    >
      <el-form :model="carForm" label-width="100px">
        <el-form-item label="车牌号">
          <el-input v-model="carForm.carNum" />
        </el-form-item>
        <el-form-item label="品牌">
          <el-input v-model="carForm.brand" />
        </el-form-item>
        <el-form-item label="指导价">
          <el-input-number v-model="carForm.guidePrice" :precision="2" :step="1000" />
        </el-form-item>
        <el-form-item label="生产时间">
          <el-date-picker
            v-model="carForm.produceTime"
            type="date"
            placeholder="选择生产日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="车型">
          <el-input v-model="carForm.carType" />
        </el-form-item>
        <el-form-item label="详细描述">
          <el-input type="textarea" v-model="carForm.description" rows="4" />
        </el-form-item>
        <el-form-item label="车辆特性">
          <el-input type="textarea" v-model="carForm.features" rows="2" placeholder="请输入车辆特性，以逗号分隔" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog
      v-model="imageDialogVisible"
      title="车辆图片"
      width="80%"
      :before-close="handleImageDialogClose"
    >
      <div class="large-image-container">
        <img :src="carImageUrl" alt="车辆大图" class="large-image" />
      </div>
    </el-dialog>

    <!-- VR看车功能预览对话框 -->
    <el-dialog
      v-model="vrDialogVisible"
      title="VR看车"
      width="90%"
      :fullscreen="isFullscreen"
      :before-close="handleVRDialogClose"
      custom-class="vr-dialog"
    >
      <template #header>
        <div class="vr-dialog-header">
          <h4>VR看车</h4>
          <div class="vr-controls">
            <el-button type="text" @click="toggleFullscreen">
              <i :class="isFullscreen ? 'el-icon-close' : 'el-icon-full-screen'"></i>
              {{ isFullscreen ? '退出全屏' : '全屏' }}
            </el-button>
          </div>
        </div>
      </template>
      <div class="vr-container">
        <div v-if="currentSu7Image" class="image-drag-container" 
             @mousedown="startDrag" 
             @mousemove="onDrag" 
             @mouseup="endDrag"
             @mouseleave="endDrag"
             @touchstart="startDragTouch"
             @touchmove="onDragTouch"
             @touchend="endDragTouch">
          <div class="drag-instruction" v-if="showDragHint">
            <i class="el-icon-d-arrow-left"></i> 
            左右拖动查看更多图片 
            <i class="el-icon-d-arrow-right"></i>
          </div>
          <img :src="currentSu7Image" alt="车辆VR预览" class="vr-image" draggable="false" />
          <div class="image-navigation">
            <el-button type="primary" @click="showPreviousImage">上一张</el-button>
            <span class="image-counter">{{ currentImageIndex + 1 }} / {{ su7Images.length }}</span>
            <el-button type="primary" @click="showNextImage">下一张</el-button>
            <el-button type="success" @click="toggleAutoPlay">
              {{ isAutoPlaying ? '停止播放' : '自动播放' }}
            </el-button>
          </div>
        </div>
        <el-empty v-else description="加载图片中...">
          <template #image>
            <el-icon style="font-size: 60px"><Loading /></el-icon>
          </template>
        </el-empty>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, watch } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getCarById, updateCar } from '@/api/car'
import CarCommentList from '@/components/CarCommentList.vue'
import CarInspectionList from '@/components/CarInspectionList.vue'
import CarAppointmentList from '@/components/CarAppointmentList.vue'
import carImageUrl from '@/assets/images/car.jpg'
import { VideoPlay, Loading } from '@element-plus/icons-vue'

const route = useRoute()
const loading = ref(false)
const carData = ref(null)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const carForm = ref({
  carId: null,
  carNum: '',
  brand: '',
  guidePrice: 0,
  produceTime: '',
  carType: '',
  description: '',
  features: ''
})

// 当前登录用户ID，从登录状态获取
// 实际项目中可能从Vuex或Pinia状态中获取
const currentUserId = ref(1) // 假设当前用户ID为1
const isAdmin = ref(true) // 假设当前用户是管理员

// 车主姓名（模拟数据）
const carOwnerName = ref('张三')
// 车主电话（模拟数据）
const carOwnerPhone = ref('13800138000')

// 解析车辆特性列表
const carFeatures = computed(() => {
  if (!carData.value || !carData.value.features) return []
  return carData.value.features.split(',').filter(item => item.trim())
})

// 获取车辆详情
const fetchCarDetail = async () => {
  loading.value = true
  try {
    const response = await getCarById(route.params.id)
    carData.value = response
    console.log('获取到车辆详情:', carData.value)
  } catch (error) {
    console.error('获取车辆详情失败:', error)
    ElMessage.error('获取车辆详情失败')
  } finally {
    loading.value = false
  }
}

// 格式化价格
const formatPrice = (price) => {
  if (!price) return '暂无价格'
  return price.toLocaleString('zh-CN', {
    style: 'currency',
    currency: 'CNY'
  })
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString()
}

// 编辑车辆
const handleEdit = () => {
  dialogTitle.value = '编辑车辆'
  carForm.value = { ...carData.value }
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  try {
    await updateCar(carForm.value)
    ElMessage.success('更新成功')
    dialogVisible.value = false
    fetchCarDetail()
  } catch (error) {
    console.error('更新失败:', error)
    ElMessage.error('更新失败')
  }
}

// 图片预览相关
const imageDialogVisible = ref(false)

// 显示车辆图片
const showCarImage = () => {
  imageDialogVisible.value = true
}

// 关闭图片预览对话框
const handleImageDialogClose = () => {
  imageDialogVisible.value = false
}

// VR看车相关
const vrDialogVisible = ref(false)
const currentImageIndex = ref(0)
const currentSu7Image = ref('')
const isAutoPlaying = ref(false)
const isFullscreen = ref(false)
let autoPlayTimer = null

// 拖动相关
const isDragging = ref(false)
const startX = ref(0)
const showDragHint = ref(true)
const dragThreshold = 50 // 触发切换图片的拖动阈值

// SU7图片列表 - 导入所有图片
const su7Images = [
  new URL('@/assets/images/su7/416244656_1712454570865_1200.webp', import.meta.url).href,
  new URL('@/assets/images/su7/416244638_1712454570656_1200.webp', import.meta.url).href,
  new URL('@/assets/images/su7/416244655_1712454570576_1200.webp', import.meta.url).href,
  new URL('@/assets/images/su7/416244663_1712454568018_1200.webp', import.meta.url).href,
  new URL('@/assets/images/su7/416244662_1712454567758_1200.webp', import.meta.url).href,
  new URL('@/assets/images/su7/416244621_1712454567732_1200.webp', import.meta.url).href,
  new URL('@/assets/images/su7/416244637_1712454565050_1200.webp', import.meta.url).href,
  new URL('@/assets/images/su7/416244629_1712454565020_1200.webp', import.meta.url).href,
  new URL('@/assets/images/su7/416244644_1712454564752_1200.webp', import.meta.url).href,
  new URL('@/assets/images/su7/416244618_1712454561594_1200.webp', import.meta.url).href,
  new URL('@/assets/images/su7/416244628_1712454561405_1200.webp', import.meta.url).href,
  new URL('@/assets/images/su7/416244601_1712454560820_1200.webp', import.meta.url).href,
  new URL('@/assets/images/su7/416244606_1712454558764_1200.webp', import.meta.url).href,
  new URL('@/assets/images/su7/416244643_1712454558653_1200.webp', import.meta.url).href,
  new URL('@/assets/images/su7/416244634_1712454558181_1200.webp', import.meta.url).href,
  new URL('@/assets/images/su7/416244605_1712454556148_1200.webp', import.meta.url).href,
  new URL('@/assets/images/su7/416244642_1712454555787_1200.webp', import.meta.url).href,
  new URL('@/assets/images/su7/416244616_1712454555296_1200.webp', import.meta.url).href,
  new URL('@/assets/images/su7/416244600_1712454553112_1200.webp', import.meta.url).href,
  new URL('@/assets/images/su7/416244599_1712454552702_1200.webp', import.meta.url).href,
  new URL('@/assets/images/su7/416244591_1712454552197_1200.webp', import.meta.url).href,
  new URL('@/assets/images/su7/416244614_1712454550346_1200.webp', import.meta.url).href,
  new URL('@/assets/images/su7/416244604_1712454549851_1200.webp', import.meta.url).href,
  new URL('@/assets/images/su7/416244597_1712454549426_1200.webp', import.meta.url).href,
  new URL('@/assets/images/su7/416244570_1712454547300_1200.webp', import.meta.url).href,
  new URL('@/assets/images/su7/416244589_1712454546872_1200.webp', import.meta.url).href,
  new URL('@/assets/images/su7/416244623_1712454546522_1200.webp', import.meta.url).href,
  new URL('@/assets/images/su7/416244622_1712454544393_1200.webp', import.meta.url).href,
  new URL('@/assets/images/su7/416244612_1712454544072_1200.webp', import.meta.url).href,
  new URL('@/assets/images/su7/416244594_1712454543654_1200.webp', import.meta.url).href,
  new URL('@/assets/images/su7/416244581_1712454541794_1200.webp', import.meta.url).href,
  new URL('@/assets/images/su7/416244586_1712454541418_1200.webp', import.meta.url).href,
  new URL('@/assets/images/su7/416244569_1712454541190_1200.webp', import.meta.url).href,
  new URL('@/assets/images/su7/416244549_1712454538795_1200.webp', import.meta.url).href,
  new URL('@/assets/images/su7/416244579_1712454538827_1200.webp', import.meta.url).href,
  new URL('@/assets/images/su7/416244585_1712454538821_1200.webp', import.meta.url).href
];

// 开始拖动（鼠标）
const startDrag = (event) => {
  // 暂停自动播放
  if (isAutoPlaying.value) {
    toggleAutoPlay();
  }
  
  isDragging.value = true;
  startX.value = event.clientX;
  // 隐藏提示
  if (showDragHint.value) {
    setTimeout(() => {
      showDragHint.value = false;
    }, 2000);
  }
};

// 拖动中（鼠标）
const onDrag = (event) => {
  if (!isDragging.value) return;
  
  const currentX = event.clientX;
  const diffX = currentX - startX.value;
  
  if (Math.abs(diffX) > dragThreshold) {
    if (diffX > 0) {
      // 向右拖动，显示上一张
      showPreviousImage();
    } else {
      // 向左拖动，显示下一张
      showNextImage();
    }
    
    // 重置起始位置
    startX.value = currentX;
  }
};

// 结束拖动（鼠标）
const endDrag = () => {
  isDragging.value = false;
};

// 开始拖动（触摸）
const startDragTouch = (event) => {
  // 暂停自动播放
  if (isAutoPlaying.value) {
    toggleAutoPlay();
  }
  
  isDragging.value = true;
  startX.value = event.touches[0].clientX;
  // 隐藏提示
  if (showDragHint.value) {
    setTimeout(() => {
      showDragHint.value = false;
    }, 2000);
  }
};

// 拖动中（触摸）
const onDragTouch = (event) => {
  if (!isDragging.value) return;
  event.preventDefault(); // 防止页面滚动
  
  const currentX = event.touches[0].clientX;
  const diffX = currentX - startX.value;
  
  if (Math.abs(diffX) > dragThreshold) {
    if (diffX > 0) {
      // 向右拖动，显示上一张
      showPreviousImage();
    } else {
      // 向左拖动，显示下一张
      showNextImage();
    }
    
    // 重置起始位置
    startX.value = currentX;
  }
};

// 结束拖动（触摸）
const endDragTouch = () => {
  isDragging.value = false;
};

// 显示下一张图片
const showNextImage = () => {
  if (currentImageIndex.value < su7Images.length - 1) {
    currentImageIndex.value++;
  } else {
    // 循环到第一张
    currentImageIndex.value = 0;
  }
  currentSu7Image.value = su7Images[currentImageIndex.value];
};

// 显示上一张图片
const showPreviousImage = () => {
  if (currentImageIndex.value > 0) {
    currentImageIndex.value--;
  } else {
    // 循环到最后一张
    currentImageIndex.value = su7Images.length - 1;
  }
  currentSu7Image.value = su7Images[currentImageIndex.value];
};

// 开始/停止自动播放
const toggleAutoPlay = () => {
  isAutoPlaying.value = !isAutoPlaying.value;
  if (isAutoPlaying.value) {
    // 开始自动播放，每110毫秒切换一次图片
    autoPlayTimer = setInterval(showNextImage, 110);
  } else {
    // 停止自动播放
    clearInterval(autoPlayTimer);
    autoPlayTimer = null;
  }
};

// 显示VR看车
const showVRView = () => {
  vrDialogVisible.value = true;
  // 从第一张图片开始展示
  currentImageIndex.value = 0;
  currentSu7Image.value = su7Images[currentImageIndex.value];
  // 显示拖动提示
  showDragHint.value = true;
};

// 关闭VR看车对话框
const handleVRDialogClose = () => {
  // 关闭对话框时停止自动播放
  if (isAutoPlaying.value) {
    toggleAutoPlay()
  }
  vrDialogVisible.value = false
}

// 监听对话框关闭事件，确保清理定时器
watch(vrDialogVisible, (newVal) => {
  if (!newVal && autoPlayTimer) {
    clearInterval(autoPlayTimer)
    autoPlayTimer = null
    isAutoPlaying.value = false
  }
})

// 组件卸载前清理定时器
onBeforeUnmount(() => {
  if (autoPlayTimer) {
    clearInterval(autoPlayTimer)
    autoPlayTimer = null
  }
})

// 切换全屏模式
const toggleFullscreen = () => {
  isFullscreen.value = !isFullscreen.value;
};

onMounted(() => {
  fetchCarDetail()
})
</script>

<style scoped>
.car-detail {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.detail-card {
  margin-bottom: 20px;
}

.mt-4 {
  margin-top: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.description-section, .features-section {
  margin-top: 20px;
}

.description-section h3, .features-section h3 {
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: bold;
}

.features-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.feature-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.appointment-card {
  margin-top: 20px;
}

.comment-card {
  margin-top: 20px;
}

.inspection-card {
  margin-top: 20px;
}

.large-image-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.large-image {
  max-width: 100%;
  max-height: 80vh;
  object-fit: contain;
}

.vr-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

.image-drag-container {
  position: relative;
  width: 100%;
  user-select: none;
  cursor: grab;
}

.image-drag-container:active {
  cursor: grabbing;
}

.vr-image {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  user-select: none;
  -webkit-user-drag: none;
}

.drag-instruction {
  position: absolute;
  top: 10px;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 14px;
  z-index: 10;
  display: flex;
  align-items: center;
  gap: 8px;
  animation: fade-in-out 3s ease-in-out;
}

@keyframes fade-in-out {
  0% { opacity: 0; }
  20% { opacity: 1; }
  80% { opacity: 1; }
  100% { opacity: 0; }
}

.image-navigation {
  margin-top: 20px;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
}

.image-counter {
  font-size: 14px;
  color: #606266;
  min-width: 80px;
  text-align: center;
}

.vr-dialog :deep(.el-dialog__header) {
  padding: 0;
  margin: 0;
}

.vr-dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #e4e7ed;
}

.vr-dialog-header h4 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.vr-controls {
  display: flex;
  align-items: center;
}

.vr-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
  height: 100%;
}

.image-drag-container {
  position: relative;
  width: 100%;
  height: 100%;
  user-select: none;
  cursor: grab;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.image-drag-container:active {
  cursor: grabbing;
}

.vr-image {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  user-select: none;
  -webkit-user-drag: none;
}

.vr-dialog:deep(.el-dialog__body) {
  padding: 0;
  overflow: hidden;
}

.vr-dialog.is-fullscreen .vr-image {
  max-height: calc(100vh - 150px);
}
</style> 